/**
 * Created by ren on 06/04/2017.
 */
import React, {Component} from 'react'
import {
  Platform,
  StatusBar,
  Image,
  ScrollView,
  RefreshControl,
  ActivityIndicator,
  TouchableWithoutFeedback,
  ListView
} from 'react-native';
import {Text, ListItem, Body, Button, Container, Left, View, Right, Header, Icon, Title} from 'native-base'
import {getSize} from '../../utils/response'
import * as api from '../../utils/api'
import * as netservice from '../../utils/netservice'
import PullToRefreshListView from 'react-native-smart-pull-to-refresh-listview'
import OrderList from './OrderList'
import PageUtil from '../../utils/PageUtil';
import NotRecord from '../../components/NotRecord'
import Picker from 'react-native-picker';
let timer1 = '',
  timer2 = ''
export default class AccountEnd extends Component {
  constructor(props) {
    super(props);
    this.PageUtil = new PageUtil();
    // 初始状态
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    let dataList = []
    this.state = {
      historyDate: new Date().getFullYear() + "-" + this.dateFormat(new Date().getMonth() + 1),
      pageIndex: 1,
      dataList: dataList,
      total: 1,
      dataSource: ds.cloneWithRows(dataList),
      isToNextPage: true
    };
  }


  componentDidMount() {
    this._pullToRefreshListView.beginRefresh()
  }

  componentWillUnmount() {
    clearTimeout(timer1)
    clearTimeout(timer2)
  }

  orderList(handle) {
    if (handle !== 'moreLoad') {
      this.setState({
        dataList: [],
        pageIndex: 1
      })
    }
    netservice.get(api.getIsBalanceList, {
      pageIndex: this.state.pageIndex,
      pageSize: 20,
      transferTime: this.state.historyDate
    }).then(response => {
      let newDataList = this.state.dataList.concat(response.records)
      if (newDataList.length === 0) {
        newDataList = [0]
      }
      this.setState({
        dataList: newDataList,
        dataSource: this.state.dataSource.cloneWithRows(newDataList),
        total: response.total,
        isToNextPage: true
      })
    })
  }

  _onRefresh() {
    //页面刷新时阻止进入下一页
    this.setState({
      isToNextPage: false
    })
    timer1 = setTimeout(() => {
      this.orderList()
      this._pullToRefreshListView.endRefresh()
    }, 1000)
  }

  toOrderDetail(balanceId) {
    this.PageUtil.jumpPageWithComponent(OrderList, {balanceId: balanceId})
  }

  loadMore() {
    //页面刷新时阻止进入下一页
    this.setState({
      isToNextPage: false
    })
    timer2 = setTimeout(() => {
      this.setState({
        pageIndex: this.state.pageIndex + 1
      })
      let length = this.state.dataList.length
      this.orderList('moreLoad')
      let loadedAll
      if (length >= this.state.total) {
        loadedAll = true
        this._pullToRefreshListView.endLoadMore(loadedAll)
      } else {
        loadedAll = false
        this._pullToRefreshListView.endLoadMore(loadedAll)
      }
    }, 1000)
  }

  renderGList(gList) {
    if (this.state.total === 0) {
      return (<NotRecord/>)
    }
    var newDate = new Date()
    var nDate = newDate.getFullYear() + '-' + (newDate.getMonth() + 1) + '-' + newDate.getDate()
    var date = (gList.transferTime).split(' ')[0];
    var flag = ''
    if (Date.parse(new Date(nDate)) !== Date.parse(new Date(date))) {
      flag = date.split('-')[1] + '-' + date.split('-')[2]
    } else {
      flag = '今天'
    }
    var time = (gList.transferTime).split(' ')[1].split(':');
    return (
      <TouchableWithoutFeedback onPress={(balanceId)=>this.toOrderDetail(gList.id)}>
        <ListItem style={{paddingRight:0,marginRight:getSize(15)}}>
          <View style={{alignItems:'center'}}>
            <Text style={{fontSize:getSize(13)}}>{flag}</Text>
            <Text style={{fontSize:getSize(13)}}>{time[0] + ':' + time[1]}</Text>
          </View>
          <Body style={{flex:getSize(10)}}>
          <Text style={{fontSize:getSize(21),color:'#FF5933'}}>+{gList.settlementAmount}</Text>
          <Text note style={{fontSize:getSize(11)}}>结算单编号:{gList.balanceCode}</Text>
          </Body>
          <Right style={{flex:2,flexDirection:'row',alignItems:'center',justifyContent:'flex-end'}}>
            <Text note style={{fontSize:getSize(13),marginRight:getSize(5)}}>{gList.orderCount}单</Text>
            <Icon name={'ios-arrow-forward'}/>
          </Right>
        </ListItem>
      </TouchableWithoutFeedback>
    );
  }

  _renderHeader = (viewState) => {
    let {pullState, pullDistancePercent} = viewState
    let {refresh_none, refresh_idle, will_refresh, refreshing,} = PullToRefreshListView.constants.viewState
    pullDistancePercent = Math.round(pullDistancePercent * 100)
    switch (pullState) {
      case refresh_none:
        return (
          <View style={{height: 50, justifyContent: 'center', alignItems: 'center'}}>
            <Text>刷新结束</Text>
          </View>
        )
      case refresh_idle:
        return (
          <View style={{height: 50, justifyContent: 'center', alignItems: 'center'}}>
            <Text>下拉刷新{pullDistancePercent}%</Text>
          </View>
        )
      case will_refresh:
        return (
          <View style={{height: 50, justifyContent: 'center', alignItems: 'center'}}>
            <Text>刷新释放{pullDistancePercent > 100 ? 100 : pullDistancePercent}%</Text>
          </View>
        )
      case refreshing:
        return (
          <View
            style={{flexDirection: 'row', height: 50, justifyContent: 'center', alignItems: 'center'}}>
            {this._renderActivityIndicator()}<Text>刷新中……</Text>
          </View>
        )
    }
  }

  _renderActivityIndicator() {
    return ActivityIndicator ? (
        <ActivityIndicator
          style={{marginRight: 10,}}
          animating={true}
          color={'#ff0000'}
          size={'small'}/>
      ) : Platform.OS == 'android' ?
        (
          <ProgressBarAndroid
            style={{marginRight: 10,}}
            color={'#ff0000'}
            styleAttr={'Small'}/>

        ) : (
          <ActivityIndicatorIOS
            style={{marginRight: 10,}}
            animating={true}
            color={'#ff0000'}
            size={'small'}/>
        )
  }

  _renderFooter = (viewState) => {
    let {pullState, pullDistancePercent} = viewState
    let {load_more_none, load_more_idle, will_load_more, loading_more, loaded_all,} = PullToRefreshListView.constants.viewState
    pullDistancePercent = Math.round(pullDistancePercent * 100)
    switch (pullState) {
      case load_more_none:
        return (
          <View style={{height: 35, justifyContent: 'center', alignItems: 'center'}}>
            <Text>上拉加载完成</Text>
          </View>
        )
      case load_more_idle:
        return (
          <View style={{height: 35, justifyContent: 'center', alignItems: 'center'}}>
            <Text>上拉加载{pullDistancePercent}%</Text>
          </View>
        )
      case will_load_more:
        return (
          <View style={{height: 35, justifyContent: 'center', alignItems: 'center'}}>
            <Text>上拉加载释放{pullDistancePercent > 100 ? 100 : pullDistancePercent}%</Text>
          </View>
        )
      case loading_more:
        return (
          <View
            style={{flexDirection: 'row', height: 35, justifyContent: 'center', alignItems: 'center'}}>
            {this._renderActivityIndicator()}<Text>加载中</Text>
          </View>
        )
      case loaded_all:
        return (
          <View style={{height: 35, justifyContent: 'center', alignItems: 'center'}}>
            <Text>已到底部</Text>
          </View>
        )
    }
  }

  _createDateData() {
    let date = [];
    for (let i = 1950; i < new Date().getFullYear() + 1; i++) {
      let month = [];
      for (let j = 1; j < 13; j++) {
        month.push(j);
      }
      let _date = {};
      _date[i] = month;
      date.push(_date);
    }
    return date;
  }

  dateFormat(str) {
    let date = str;
    if (parseInt(str) < 10) {
      date = '0' + str;
    }
    return date
  }

  _showDatePicker() {
    let historyDateArray = (this.state.historyDate).split('-')
    Picker.init({
      pickerCancelBtnText: '取消',
      pickerConfirmBtnText: '确定',
      pickerTitleText: '请选择结算日期',
      pickerData: this._createDateData(),
      pickerToolBarFontSize: 16,
      pickerFontSize: 16,
      selectedValue: [parseInt(historyDateArray[0]), parseInt(historyDateArray[1])],
      pickerFontColor: [0, 0, 0, 1],
      onPickerConfirm: (pickedValue, pickedIndex) => {
        this.setState({
          historyDate: pickedValue[0] + '-' + this.dateFormat(pickedValue[1])
        })
        this._onRefresh()
      },
      onPickerCancel: (pickedValue, pickedIndex) => {
        console.log('date', pickedValue, pickedIndex);
      },
      onPickerSelect: (pickedValue, pickedIndex) => {
        console.log('date', pickedValue, pickedIndex);
      }
    });
    Picker.show();
  }
  componentWillUnmount() {
    Picker.hide()
  }
  render() {
    const {historyDate}=this.state
    return (
      <Container
        style={{flex:1,backgroundColor:'#F4F4F4'}}>
        <Header iosBarStyle="light-content" backgroundColor="#FF562F"
                style={{backgroundColor:'#FF562F',borderBottomWidth:0}}>
          <StatusBar
            backgroundColor={'#303135'}
          />
          <Left style={{flex:1}}>
            <Button transparent onPress={this.PageUtil.pop}>
              <Icon name='arrow-back' style={{fontSize:getSize(24),color:'white'}}/>
            </Button>
          </Left>
          <Body style={{alignItems:'center'}}>
          <Title style={{color:'white',fontSize:getSize(19)}}>已结算单</Title>
          </Body>
          <Right style={{flex:1}}>
          </Right>
        </Header>
        <View
          style={{height:getSize(36),flexDirection:'row',paddingLeft:getSize(20),paddingRight:getSize(15),alignItems:'center'}}>
          <Text
            style={{fontSize:getSize(13),color:'#333333'}}>{historyDate.split('-')[0]}年{historyDate.split('-')[1]}月</Text>
          <Right>
            <TouchableWithoutFeedback onPress={this._showDatePicker.bind(this)}>
              <View style={{flexDirection:'row',alignItems:'center'}}>
                <Text style={{fontSize:getSize(13),color:'#B4B4B4',marginRight:getSize(5)}}>历史订单</Text>
                <Icon name='ios-arrow-forward' style={{fontSize:getSize(18),color:'#B4B4B4'}}/>
              </View>
            </TouchableWithoutFeedback>
          </Right>
        </View>
        <PullToRefreshListView
          style={{backgroundColor:'white'}}
          ref={ (component) => this._pullToRefreshListView = component }
          viewType={PullToRefreshListView.constants.viewType.listView}
          initialListSize={20}
          enableEmptySections={true}
          dataSource={this.state.dataSource}
          pageSize={1000}
          renderRow={(gList)=>this.renderGList(gList)}
          renderHeader={this._renderHeader}
          renderFooter={this._renderFooter}
          onRefresh={()=>this._onRefresh()}
          onLoadMore={()=>this.loadMore()}
          pullUpDistance={35}
          pullUpStayDistance={50}
          pullDownDistance={35}
          pullDownStayDistance={50}
        />
      </Container>
    );
  }
}
const styles = {

  listItem: {
    backgroundColor: 'white',
    marginLeft: 0,
    marginBottom: 9,
    paddingTop: 0,
    paddingBottom: 0,
    paddingLeft: 10,
    paddingRight: 10
  },
  listHeader: {
    flexDirection: 'row',
    borderBottomWidth: 1 / 3,
    height: getSize(22.5),
    alignItems: 'center',
    borderBottomColor: '#95989A',
    marginBottom: getSize(6.5)
  },
  imgWrap: {
    borderWidth: 1,
    borderColor: '#C6C6C6',
    width: getSize(80),
    height: getSize(80),
    justifyContent: 'center',
    alignItems: 'center'
  },
  btn: {
    width: getSize(65),
    height: getSize(26),
    backgroundColor: '#16BD42',
    justifyContent: 'center'
  },
  btn1: {
    width: getSize(65),
    height: getSize(26),
    backgroundColor: '#FFA83F',
    justifyContent: 'center',
    marginRight: getSize(23)
  },
  butText: {
    textAlign: 'center',
    width: getSize(65),
    fontSize: getSize(15),
    height: getSize(26),
    lineHeight: parseInt(getSize(24))
  }
};